<template>
  <el-dialog :visible.sync="visible" top="20px" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="140px">
      <el-form-item prop="templeteName" :label="$t('templete.templeteName')">
        <el-input v-model="dataForm.templeteName" :placeholder="$t('templete.templeteName')"/>
      </el-form-item>
      <template v-hasPermi="['sys:template:save']">
      <el-form-item prop="lib" label="模板库">
        <el-radio v-model="dataForm.lib" :label="1">公共模板库</el-radio>
        <el-radio v-model="dataForm.lib" :label="2">私有模板库</el-radio>
      </el-form-item>
      <el-form-item prop="companyId" :label="$t('templete.companyName')" v-if="dataForm.lib == 2">
        <el-select
                v-model="dataForm.companyId"
                filterable
                remote
                clearable
                reserve-keyword
                placeholder="请输入企业名称关键词"
                :remote-method="remoteMethod"
                :loading="loading"
                style="width: 100%"  >
          <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="costType" :label="$t('templete.costType')">
        <el-select v-model="dataForm.costType" :value="dataForm.costType"
                   placeholder="请选择计费方式"
                   style=" width: 180px;">
          <el-option
                  v-for="item in costTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="payAmount" :label="$t('templete.payAmount')" v-if="dataForm.costType === 1">
        <el-input-number name="payAmount" v-model="dataForm.payAmount"  min="0"  :step="10" :max="10000000" style="margin-right: 10px;"></el-input-number>元
      </el-form-item>
      <el-form-item prop="payRatio" :label="$t('templete.payRatio')" v-if="dataForm.costType === 2">
        <el-input-number name="payRatio" v-model.number="payRatioInput" :min="0.1" :step="0.1" :precision="1" :max="10000000" style="margin-right: 10px;"></el-input-number><b style="font-size: 25px">‰</b> <b style="color: red;margin-left: 20px">注: 合同金额*比例系数</b>
      </el-form-item>
      <el-form-item prop="minAmount" label="最低金额" v-if="dataForm.costType === 2">
        <el-input-number name="minAmount" v-model.number="dataForm.minAmount" :min="0" :step="1" :max="10000000" style="margin-right: 10px;"></el-input-number>元
      </el-form-item>
      </template>
      <el-form-item label="模板文档:" style="margin-bottom: 15px;" v-if="!dataForm.id">
        <el-upload
                class="upload-demo"
                ref="upload"
                :action="uploadUrl()"
                :before-upload="beforeAvatarUploadDetail"
                :file-list="fileList"
                :limit="1"
                :data="dataType"
                :headers="headers()"
                :on-success="handleSuccessDetail">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传一个docx文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item prop="remark" :label="$t('remark')">
        <el-input v-model="dataForm.remark" :placeholder="$t('remark')"/>
      </el-form-item>

    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { debounce } from 'lodash'
import Cookies from 'js-cookie'

let tokenStr = Cookies.get('token');

export default {
  data () {
    return {
      visible: false,
      fileList: [],
      companyList: [],
      loading: false,
      dataType: {
        type: 'TEMPLETE'
      },
      costTypeOptions:[{
        label: '按模板计费',
        value: 1
      }, {
        label: '按合同金额计费',
        value: 2
      }],
      payRatioInput: 1,
      dataForm: {
        companyId: '',
        id: 0,
        costType: 1,
        payAmount: 80,
        payRatio: 0.001,
        minAmount: 80,
        templeteName: '',
        templetePath: '',
        remark: '',
        lib: 1
      }
    }
  },
  computed: {
    dataRule () {
      return {
        templeteName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        companyId: [
          { required: this.dataForm.lib === 2, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.fileList = []
        Promise.all([

        ]).then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }
        })
      })
    },

    headers(){
      return{
        'token': tokenStr
      }
    },

    // 获取信息
    getInfo () {
      this.$axios.get(`/manager/template/info/${this.dataForm.id}`).then(res => {
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.payRatioInput = JSON.parse(JSON.stringify(this.dataForm)).payRatio * 1000
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        if (this.dataForm.lib === 1) {
          this.dataForm.companyId = 0
        }
        this.dataForm.payRatio = this.payRatioInput / 1000
        // this.dataForm.menuIdList = JSON.stringify(this.dataForm.menuIdList)
        this.$http.json('/manager/template/addOrUpdate', this.dataForm).then(res => {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),


    beforeAvatarUploadDetail (file) {
      const isDocx = file.name.toString().toLowerCase().indexOf('docx')
      if (!isDocx) {
        this.$message.error('上传文档只能是 DOCX 格式!')
      }
      return isDocx
    },
    uploadUrl () {
      return process.env.VUE_APP_API + "/file/upload"
    },

    //文件上传成功返回文件路径
    handleSuccessDetail (response, file, fileList) {
      if (response.code === 100) {
        this.dataForm.templetePath = response.data
      } else {
        this.$message.error(response.msg)
      }
    },

    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.getCompanyList(query);
      } else {
        this.companyList = [];
      }
    },

    // 获企业客户所列表
    getCompanyList(queryName) {
      return this.$axios.get('/manager/company/page', {
        params: {
          order: 'ASC',
          orderField: 'createTime',
          current: 1,
          size: 20,
          listMode: true,
          queryItems: 'name,LIKE,' + queryName
        }
      }).then(res => {
        this.loading = false;
        this.companyList = res.data.records
      }).catch(() => {
      })
    },

  }
}
</script>
